<?php
namespace App\Admin\Controllers\ProductStockup;

use App\Importer\Basics\BImporter;
use App\Models\Product\ProductSku;
use App\Models\ProductStockup\StockupSkuPackingSpec;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class StockupSkuPackingSpecUploadController extends AdminController{

    protected $title = 'sku规格';

    protected function grid()
    {
        $type = request('type');
        return view("product-stockup.stockup-sku-packing-spec-upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $re = $this->_importSpec($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importSpec(UploadedFile $file){
        try{
            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];

            $errors = [];
            $count = 1;
            $skuArr = [];

            DB::beginTransaction();
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $numPerBox = is_null($row[1]) ? null : trim($row[1]);
                if(!$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($sku,$skuArr)){
                    $skuArr[$count] = $sku;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $skuPackingSpec = StockupSkuPackingSpec::query()->firstOrNew(['psku_id' => $pSkuId]);
                if(!is_null($numPerBox)){
                    $skuPackingSpec->num_per_box = $numPerBox;
                }
                $skuPackingSpec->save();
            }
            DB::commit();
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
